// 为了方便管理请求接口，所有的请求都以异步 action 的方式进行封装
import http from '@/utils/request'
import { removeLocalHistories, setLocalHistories } from '@/utils/storage'
import store, { AppDispatch } from '..'
import { SearchAction } from '../reducer/search'

/**
 * 获取联想建议（自动补全）
 * @param q
 * @returns
 */
export const getSuggestionAPI = (q: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/suggestion?q=${q}`)
    dispatch({ type: 'search/saveSuggestion', payload: res.data.options })
  }
}
/**
 * 清空输入框
 * @returns
 */
export const clearSuggestionAPI = (): SearchAction => {
  return { type: 'search/clearSuggestion' }
}

/**
 * 历史记录
 * @returns
 */
export const addHistoryAPI = (keyword: string) => {
  return (dispatch: AppDispatch) => {
    //  获取原来的历史记录
    const { histories } = store.getState().search
    // 数组去重
    const newHistories = Array.from(new Set([...histories, keyword]))
    // 数量限制最多为10条
    if (newHistories.length > 10) newHistories.length = 10
    // 保存 Rudex
    dispatch({ type: 'search/saveHistorys', payload: newHistories })
    // 保存到本地
    setLocalHistories(newHistories)
  }
}

/**
 * 清理搜索历史记录
 * @returns
 */
export const clearHistoryAPI = (): SearchAction => {
  // 清除本地
  removeLocalHistories()
  return { type: 'search/cleaHistory' }
}

type SearchQuery = {
  per_page?: number
  page?: number
  q: string
}

/**
 * 获取搜索结果
 * @param param0
 * @returns
 */
export const getSearchResultAPI = ({
  per_page = 10,
  page = 1,
  q = '',
}: SearchQuery) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get('/v1_0/search', {
      params: { per_page, page, q },
    })
    //  获取原本的搜索列表
    const { results } = store.getState().search
    // 分页需要把新旧搜索列表合并在一起
    dispatch({
      type: 'search/saveResult',
      payload: [...results, ...res.data.results],
    })
    // 分页停止条件: 返回列表长度 < 页容量
    if (res.data.results.length < per_page) {
      // console.log('分页结束,需要停下来')
      // 方案1: 返回一个表示错误的 Promise, catch 会捕获到错误的 Promise
      return Promise.reject('没有更多分页了...')
      // 方案2: 制造一个错误对象, catch 会捕获到错误对象
      // throw new Error('没有更多分页了...')
    }
  }
}

/**
 * 清空搜索结果
 * @returns
 */
export const clearSearchResultAPI = () => {
  return async (dispatch: AppDispatch) => {
    dispatch({ type: 'search/clearResult' })
  }
}
